package com.example.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * description: BlockingQueueDemo <br>
 * date: 2021/3/22 16:28 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
        //addAndRemove(queue);

        //offerAndPoll(queue);
        
//        putAndTake(queue);

        outOfTime(queue);
    }

    private static void outOfTime(BlockingQueue<String> queue) throws InterruptedException {
        System.out.println(queue.offer("aa==", 2, TimeUnit.SECONDS));
        System.out.println(queue.offer("bb==", 2, TimeUnit.SECONDS));
        System.out.println(queue.offer("cc==", 2, TimeUnit.SECONDS));
        // 这里因为队列只有三个位置，插入第四个会失败，所以会触发这个超时时间两秒后打印出false
        System.out.println(queue.offer("dd==", 2, TimeUnit.SECONDS));

        System.out.println(queue.poll(10, TimeUnit.SECONDS));
        System.out.println(queue.poll(10, TimeUnit.SECONDS));
        System.out.println(queue.poll(10, TimeUnit.SECONDS));
    }

    private static void putAndTake(BlockingQueue<String> queue) throws InterruptedException {
        queue.put("aaa");
        queue.put("bbb");
        queue.put("ccc");

        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
    }

    private static void offerAndPoll(BlockingQueue<String> queue) {
        System.out.println(queue.offer("aa"));
        System.out.println(queue.offer("bb"));
        System.out.println(queue.offer("cc"));
        System.out.println(queue.offer("dd"));
    }

    private static void addAndRemove(BlockingQueue<String> queue) {
        queue.add("a");
        queue.add("b");
        queue.add("c");
        //queue.add("d");
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
    }

}
